package com.example.runningman.fragment;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import jp.wasabeef.glide.transformations.BlurTransformation;
import jp.wasabeef.glide.transformations.CropCircleTransformation;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;


import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.runningman.BuildConfig;
import com.example.runningman.R;
import com.example.runningman.bean.Art;
import com.example.runningman.bean.BaiduPoints;
import com.example.runningman.dao.PointsDao;
import com.example.runningman.database.BaiduPointsDatebase;
import com.example.runningman.friend.SelfActivity;
import com.example.runningman.run.CountryActivity;
import com.example.runningman.run.DynamicDemo;
import com.example.runningman.run.StaticDemo;
import com.example.runningman.user.AchieActivity;
import com.example.runningman.user.ChangepswActivity;
import com.example.runningman.user.LoginActivity;
import com.example.runningman.user.UserActivity;
import com.example.runningman.util.GlideBlurTransformation;
import com.example.runningman.util.SPUtil;
import com.example.runningman.view.ItemView;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import static com.example.runningman.util.BitmapUtil.compressImage;

/**
 * A simple {@link Fragment} subclass.
 */
public class ProfileFragment extends BaseFragment implements View.OnClickListener {
    ImageView imageView_head;
    ImageView imageView;
    ItemView conten;
    ItemView cgpsw;
    ItemView country;
    TextView textView;
    TextView textname;
    String phone;
    ItemView achi;
    int IMG_FROMALBUM_NOCROP = 0;

    public ProfileFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_profile, container, false);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        phone=SPUtil.getInstance(getActivity()).getString("phone","17654452115");
        imageView_head = getActivity().findViewById(R.id.h_head);
        imageView = getActivity().findViewById(R.id.h_back);
        conten = getActivity().findViewById(R.id.conten);
        cgpsw = getActivity().findViewById(R.id.item2);
        achi = getActivity().findViewById(R.id.item3);
        String s=SPUtil.getInstance(getActivity()).getString("photo",R.drawable.h_head+"");
        mHandler=new Mhandler();
        Glide.with(getActivity()).load(s)
                .apply(RequestOptions.bitmapTransform(new GlideBlurTransformation(getActivity())))
                .into(imageView);
        country = getActivity().findViewById(R.id.country);
        Glide.with(getActivity()).load(s)
                .apply(RequestOptions.bitmapTransform(new RoundedCorners(60)))
                .into(imageView_head);
        textView=getActivity().findViewById(R.id.user_val);

        textView.setText(phone.substring(0,3)+"****"+phone.substring(7,11));
        textname=getActivity().findViewById(R.id.user_name) ;
        textname.setText(SPUtil.getInstance(getActivity()).getString("username","张三"));
        imageView_head = getActivity().findViewById(R.id.h_head);
        imageView_head.setOnClickListener(this::onClick);
        conten.setOnClickListener(this::onClick);
        cgpsw.setOnClickListener(this::onClick);
        country.setOnClickListener(this::onClick);
        achi.setOnClickListener(this::onClick);
//        dyn=getActivity().findViewById(R.id.dyn);
//        dyn.setOnClickListener(this::onClick);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.conten:

                intent = new Intent(getActivity(), UserActivity.class);
                startActivity(intent);
                break;
            case R.id.h_head:
                Intent intentToPickPic = new Intent(Intent.ACTION_PICK, null);
                intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");

                startActivityForResult(intentToPickPic, RC_CHOOSE_PHOTO);
//                Intent intentToTakePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                File fileDir = new File(Environment.getExternalStorageDirectory() + File.separator + "photoTest" + File.separator);
//                if (!fileDir.exists()) {
//                    fileDir.mkdirs();
//                }
//
//                File photoFile = new File(fileDir, "photo.jpeg");
//                mTempPhotoPath = photoFile.getAbsolutePath();
//                imageUri = FileProvider.getUriForFile(getActivity(), "com.example.runningman.fileprovider",photoFile);
//                intentToTakePhoto.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//                startActivityForResult(intentToTakePhoto, RC_TAKE_PHOTO);
                break;
            case R.id.item2:
                intent = new Intent(getActivity(), ChangepswActivity.class);
                startActivity(intent);
                break;
            case R.id.country:
                intent = new Intent(getActivity(), CountryActivity.class);
                startActivity(intent);
                break;
            case R.id.item3:
                intent = new Intent(getActivity(), AchieActivity.class);
                startActivity(intent);
            default:
                break;
        }
    }
    private String mTempPhotoPath;
    private Uri imageUri;
    public static final int RC_TAKE_PHOTO = 1;
    public static final int RC_CHOOSE_PHOTO = 2;
    @Override
    public void onActivityResult(int requestCode, int resultCode, final Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case RC_CHOOSE_PHOTO:
                Uri uri = data.getData();
                String filePath = FileUtil.getFilePathByUri(getActivity(), uri);
                filePath = compressImage(filePath);
                if (!TextUtils.isEmpty(filePath)) {
                    RequestOptions requestOptions1 = new RequestOptions().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE);
                    //将照片显示在 ivImage上

                    Glide.with(getActivity()).load(filePath)
                            .apply(RequestOptions.bitmapTransform(new GlideBlurTransformation(getActivity())))
                            .into(imageView);
                    SPUtil.getInstance(getActivity()).putString("photo",filePath);
                    postRequest(filePath);
                    Glide.with(getActivity()).load(filePath)
                            .apply(RequestOptions.bitmapTransform(new RoundedCorners(60)))
                            .into(imageView_head);
                }
                break;
            case RC_TAKE_PHOTO:
                RequestOptions requestOptions = new RequestOptions().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE);
                //将图片显示在ivImage上

                Glide.with(getActivity()).load(mTempPhotoPath).apply(requestOptions)
                        .apply(RequestOptions.bitmapTransform(new GlideBlurTransformation(getActivity())))
                        .into(imageView);
                SPUtil.getInstance(getActivity()).putString("photo",imageToBase64(mTempPhotoPath));
                //postRequest(imageToBase64(mTempPhotoPath),SPUtil.getInstance(getActivity()).getString("phone"));
                Glide.with(getActivity()).load(mTempPhotoPath).apply(requestOptions)
                        .apply(RequestOptions.bitmapTransform(new RoundedCorners(60)))
                        .into(imageView_head);
                break;
        }
    }
    /**
     * 将图片转换成Base64编码的字符串
     */
    public static String imageToBase64(String path){
        if(TextUtils.isEmpty(path)){
            return null;
        }
        InputStream is = null;
        byte[] data = null;
        String result = null;
        try{
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            is.read(data);
            //用默认的编码格式进行编码
            result = Base64.encodeToString(data,Base64.NO_CLOSE);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(null !=is){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return result;
    }

    private Mhandler mHandler;


    private  class Mhandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){
                String ReturnMessage = (String) msg.obj;
                Log.i("获取的返回信息",ReturnMessage);
                SPUtil.getInstance(getActivity()).putString("photo",ReturnMessage);

                /***
                 * 在此处可以通过获取到的Msg值来判断
                 * 给出用户提示注册成功 与否，以及判断是否用户名已经存在
                 */

            }
        }
    }

    final OkHttpClient client = new OkHttpClient();
    private void postRequest(String filePath)  {
        //建立请求表单，添加上传服务器的参数
        Log.e("sss", filePath);
        String fileName=filePath.substring(filePath.lastIndexOf("."));
        RequestBody formBody = new MultipartBody.Builder()
                .addFormDataPart("file", fileName,
                        RequestBody.create(MediaType.parse("multipart/form-data"), new File(filePath)))
                .addFormDataPart("phone",phone)
                .build();
        //发起请求
        final Request request = new Request.Builder()
                .url("http://120.26.177.58:8080/AndroidServer01/addUserImg?")
                .post(formBody)
                .build();
        //新建一个线程，用于得到服务器响应的参数
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                        mHandler.obtainMessage(1, response.body().string()).sendToTarget();

                    } else {
                        throw new IOException("Unexpected code:" + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

}
